package com.cloudkinto.controller.company;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.vo.company.CompanyPageVo;
import com.cloudkinto.vo.company.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.company.CompanyService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.cloudkinto.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author 张永远
 * @since 2020-05-27
 */
@RestController
@Api(tags = "公司omp模块")
@RequestMapping("/api/admin/omp/company")
public class CompanyOmpController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(CompanyOmpController.class);

    @Autowired
    private CompanyService service;

    //    @PostMapping("")
//    @ApiOperation(value = "新增", notes = "新增")
//    public SingleResult add(@RequestBody @Validated Object req) {
//        Long userId = getCurrentUserId();
//        return SingleResult.success("新增成功",service.add(req,userId));
//    }
//
//    @GetMapping("/updateInit/{id}")
//    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
//    public SingleResult updateInit(@PathVariable("id") Long id) {
//        return service.updateInit(id);
//    }
//
    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "客户修改", notes = "客户修改")
    public SingleResult update(@RequestBody @Validated CompanyUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, getTenantId(StaticDict.System_Source.OMP.getValue()), userId));
    }

    //
//    @DeleteMapping("/{id}")
//    @ApiOperation(value = "根据id删除", notes = "根据id删除")
//    public SingleResult delete(@PathVariable("id") Long id) {
//        Long userId = getCurrentUserId();
//        return SingleResult.success("删除成功",service.delete(id,userId));
//    }
//
    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = CompanyDetailRes.class))
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id, getCurrentUserId(), getTenantId(StaticDict.System_Source.OMP.getValue()), "omp"));
    }

//    @UserSessionRequired
//    @GetMapping("/list")
//    @ApiOperation(value = "公司列表", notes = "公司列表")
//    public SingleResult list(HttpServletRequest request) {
//        return SingleResult.success(service.getList(getTenantId()));
//    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "companyName", value = "公司名称"),
            @ApiImplicitParam(name = "adminAccount", value = "OMS管理员账号"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
            @ApiImplicitParam(name = "customerQuery", value = "客户名称/代码"),
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = CompanyPageVo.class))
    public PageResult listPage(HttpServletRequest request) {
        Map<String, Object> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String companyName = request.getParameter("companyName");
        String adminAccount = request.getParameter("adminAccount");
        String customerQuery = request.getParameter("customerQuery");
        String status = request.getParameter("status");
        map.put("companyName", companyName);
        map.put("adminAccount", adminAccount);
        map.put("customerQuery", customerQuery);
        map.put("status", status);
        map.put("tenantId", getTenantId(StaticDict.System_Source.OMP.getValue()));
        map.put("userId", getCurrentUserId());
        map.put("source", "omp");

        return map;
    }

//    @GetMapping("/tree")
//    @ApiOperation(value = "公司店铺联级", notes = "公司列表")
//    public SingleResult tree(HttpServletRequest request){
//        return service.tree();
//    }


    @UserSessionRequired
    @GetMapping("/getCompanyList")
    @ApiOperation(value = "获取公司列表(会被用户权限限制)", notes = "")
    @ApiImplicitParams({
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = CompanyRes.class))
    public SingleResult getCompanyList() {
        return SingleResult.success("查询成功",
                service.getCompanyList(getCurrentUserId(), getTenantId(StaticDict.System_Source.OMP.getValue()), StaticDict.System_Source.OMP.getValue()));
    }


    @UserSessionRequired
    @GetMapping("/getAllCompanyList")
    @ApiOperation(value = "获取公司列表(所有公司无视权限)", notes = "")
    @ApiImplicitParams({
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = CompanyRes.class))
    public SingleResult getAllCompanyList() {
        return SingleResult.success("查询成功", service.getCompanyList(getCurrentUserId(), getTenantId(StaticDict.System_Source.OMP.getValue()), StaticDict.System_Source.WMS.getValue()));
    }



    @UserSessionRequired
    @PostMapping("/addCompany")
    @ApiOperation(value = "客户新增", notes = "新增")
    public SingleResult addCompany(@RequestBody @Validated CompanyAddReq req) {
        Long userId = getCurrentUserId();
        service.addCompany(req, getTenantId(StaticDict.System_Source.OMP.getValue()), userId, true);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/setStorage")
    @ApiOperation(value = "设置可用仓", notes = "设置可用仓")
    public SingleResult setStorage(@RequestBody @Validated CompanySetStorageReq req) {
        Long userId = getCurrentUserId();
        service.setStorage(req, getTenantId(StaticDict.System_Source.OMP.getValue()), userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/productFreeTrial")
    @ApiOperation(value = "取消免审核/设置审核", notes = "取消免审核/设置审核")
    public SingleResult productFreeTrial(@RequestBody @Validated ProductFreeTrialReq req) {
        Long userId = getCurrentUserId();
        service.productFreeTrial(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/updateStatus")
    @ApiOperation(value = "启用 禁用", notes = "")
    public SingleResult updateStatus(@RequestBody @Validated UpdateStatusReq req) {
        Long userId = getCurrentUserId();
        service.updateStatus(req, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/resetPassword")
    @ApiOperation(value = "重设密码", notes = "")
    public SingleResult resetPassword(@RequestBody @Validated ResetPasswordReq req) {
        Long userId = getCurrentUserId();
        service.resetPassword(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/templateDownload")
    @ApiOperation(value = "下载导入模板", notes = "")
    public void templateDownload(HttpServletResponse response) {
        service.templateDownload(getTenantId(StaticDict.System_Source.OMP.getValue()), response);
    }


    @UserSessionRequired
    @PostMapping("/templateImport")
    @ApiOperation(value = "导入客户列表")
    public SingleResult templateImport(MultipartFile file) {
        CompanyImportRes res = service.templateImport(file, getTenantId(StaticDict.System_Source.OMP.getValue()), getCurrentUserId());
        return SingleResult.success(res);
    }

    @UserSessionRequired
    @GetMapping("/companyExport")
    @ApiOperation(value = "导出客户列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "勾选数据id", dataType = "arr"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "companyName", value = "公司名称"),
            @ApiImplicitParam(name = "adminAccount", value = "OMS管理员账号"),
            @ApiImplicitParam(name = "customerQuery", value = "客户名称/代码"),
    })
    public void companyExport(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = this.getMap(request);
        String ids = request.getParameter("ids");
        if (ids != null) {
            map.put("ids", Arrays.asList(ids.split(",")));
        }
        service.companyExport(map, response);
    }



    @UserSessionRequired
    @PostMapping("getTokenForOms")
    @ApiOperation(value = "跳转oms登录", notes = "跳转oms登录")
    public SingleResult getTokenForOms(@RequestBody @Validated TokenForOmsReq req, HttpServletRequest request) {
        return SingleResult.success("登录成功", service.getTokenForOms(req, request, getCurrentUserId()));
    }

}

